<template>
    <!-- 包括页头、页尾以及登录注册等基本功能 -->
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 80px'
        }" style="background-color: rgb(240,242,245);">
            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 10px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="center">
                                        <span style="display: flex; justify-content: center;">个人中心</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <span style="display: flex; justify-content: center;">我的收藏</span>
                                    </a-menu-item>
                                    <a-menu-item key="interest">
                                        <span style="display: flex; justify-content: center;">我的关注</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <span style="display: flex; justify-content: center;">退出登录</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
            </a-layout-header>
            <a-layout-content>
                <a-layout style="padding: 24px 0"
                          :style="{ backgroundImage: 'url(' + backGroundImg2 + ')', backgroundRepeat: 'no-repeat', backgroundSize: '1600px 200px'}">
                    <div style="margin-left: 230px; width: 400px; display: flex; align-items: center;">
                        <user-outlined style="font-size: 100px" />
                        <div style="margin-left: 30px">
                            <span style="color:#0B0E47; font-size: 20px">
                                您好，欢迎您
                            </span>
                            <br/>
                            <span style="color:#6C6C6C; font-size: 16px">
                                UID:{{ userFormState.id }}
                            </span>
                        </div>
                    </div>
                    <a-layout style="margin-top: 30px; margin-left: 200px; margin-right: 200px">
                        <a-layout-sider style="background: white">
                            <a-menu
                                    v-model:selectedKeys="selectedKeys"
                                    v-model:openKeys="openKeys"
                                    mode="inline"
                                    style="height: 100%"
                                    @click="handleMenuItem"
                            >
                                <a-sub-menu key="sub1">
                                    <template #title>
                                        <span>
                                          <user-outlined/>
                                          用户信息
                                        </span>
                                    </template>
                                    <a-menu-item key="1">基本信息</a-menu-item>
                                    <a-menu-item key="2">修改密码</a-menu-item>
                                </a-sub-menu>
                                <a-sub-menu key="sub2">
                                    <template #title>
                                        <span>
                                          <star-outlined />
                                          收藏关注
                                        </span>
                                    </template>
                                    <a-menu-item key="3">论文收藏</a-menu-item>
                                    <a-menu-item key="4">作者关注</a-menu-item>
<!--                                    <a-menu-item key="5">检索式订阅</a-menu-item>-->
                                </a-sub-menu>
                                <a-sub-menu key="sub3">
                                    <template #title>
                                        <span>
                                          <history-outlined />
                                          历史记录
                                        </span>
                                    </template>
<!--                                    <a-menu-item key="6">下载历史</a-menu-item>-->
                                    <a-menu-item key="7">浏览历史</a-menu-item>
                                    <a-menu-item key="8">检索历史</a-menu-item>
                                </a-sub-menu>
                            </a-menu>
                        </a-layout-sider>
                        <a-layout-content v-if="currentKey==1" :style="{ padding: '0 24px', minHeight: '280px', background: 'white' }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="基本信息">
                                    <a-form
                                            :model="userFormState"
                                            name="basic"
                                            :label-col="{ span: 6 }"
                                            :wrapper-col="{ span: 12 }"
                                            autocomplete="off"
                                            @finish="onUserFinish"
                                            @finishFailed="onUserFinishFailed"
                                    >
                                        <a-form-item
                                                label="用户名"
                                                name="username"
                                                :required="true"
                                        >
                                            <a-input v-model:value="userFormState.username" :disabled="true" />
                                        </a-form-item>

                                        <a-form-item
                                                label="姓名"
                                                name="realname"
                                        >
                                            <a-input v-model:value="userFormState.realname" />
                                        </a-form-item>

                                        <a-form-item
                                                label="性别"
                                                name="gender"
                                        >
                                            <a-radio-group v-model:value="userFormState.gender">
                                                <a-radio :value="1">男</a-radio>
                                                <a-radio :value="2">女</a-radio>
                                            </a-radio-group>
                                        </a-form-item>

                                        <a-form-item
                                                name="major"
                                                label="学历"
                                        >
                                            <a-select v-model:value="userFormState.major">
                                                <a-select-option :value="0">请选择</a-select-option>
                                                <a-select-option :value="1">本科</a-select-option>
                                                <a-select-option :value="2">研究生</a-select-option>
                                                <a-select-option :value="3">博士生</a-select-option>
                                            </a-select>
                                        </a-form-item>

                                        <a-form-item
                                                label="工作单位"
                                                name="workplace"
                                        >
                                            <a-input v-model:value="userFormState.workplace" />
                                        </a-form-item>

                                        <a-form-item
                                                label="研究方向"
                                                name="researchfield"
                                        >
                                            <a-input v-model:value="userFormState.researchfield" />
                                        </a-form-item>

                                        <a-form-item
                                                label="邮箱"
                                                name="email"
                                        >
                                            <a-input v-model:value="userFormState.email" />
                                        </a-form-item>

                                        <a-form-item
                                                label="电话"
                                                name="phone"
                                        >
                                            <a-input v-model:value="userFormState.phone" />
                                        </a-form-item>

                                        <hr class="custom-divider" />

                                        <a-form-item :wrapper-col="{ offset: 8, span: 8 }">
                                            <a-button type="primary" html-type="submit" style="width: 40%">保存</a-button>
                                            <a-button type="primary" style="margin-left: 20%; width: 40%; background-color: #BBBBBB; border: none;">注销</a-button>
                                        </a-form-item>
                                    </a-form>
                                </a-tab-pane>
                            </a-tabs>
                        </a-layout-content>
                        <a-layout-content v-if="currentKey==2" :style="{ padding: '0 24px', minHeight: '280px', background: 'white' }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="修改密码">
                                    <a-form
                                            ref="passFormRef"
                                            name="custom-validation"
                                            :model="passFormState"
                                            :rules="passRules"
                                            :label-col="{ span: 6 }"
                                            :wrapper-col="{ span: 12 }"
                                            @finish="onPassFinish"
                                            @validate="handlePassValidate"
                                            @finishFailed="onPassFinishFailed"
                                    >
                                        <a-form-item label="原密码" name="originPass"
                                                     :rules="[{ required: true, message: '请输入原密码' }]">
                                            <a-input v-model:value="passFormState.originPass" type="password" autocomplete="off" />
                                        </a-form-item>
                                        <a-form-item has-feedback label="新密码" name="newPass">
                                            <a-input v-model:value="passFormState.newPass" type="password" autocomplete="off" />
                                        </a-form-item>
                                        <a-form-item has-feedback label="确认密码" name="checkPass">
                                            <a-input v-model:value="passFormState.checkPass" type="password" autocomplete="off" />
                                        </a-form-item>

                                        <a-form-item :wrapper-col="{ span: 8, offset: 8 }">
                                            <a-button type="primary" html-type="submit" style="width: 40%">修改</a-button>
                                            <a-button style="margin-left: 20%; width: 40%;" @click="resetPassForm">清空</a-button>
                                        </a-form-item>
                                    </a-form>
                                </a-tab-pane>
                            </a-tabs>

                        </a-layout-content>
                        <a-layout-content v-if="currentKey==3" :style="{ padding: '0 24px', minHeight: '280px', background: 'white'  }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="论文收藏">
                                    <a-table :columns="paperColumns" :data-source="paperList" bordered :pagination="false">
                                        <template #bodyCell="{ column, text, record }">
                                            <template v-if="column.dataIndex === 'title'">
                                                <span :style="{ color: record.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: record.isTitleHovered ? 'underline' : 'none' , fontSize: '16px', cursor: 'pointer'}"
                                                      @mouseover="record.isTitleHovered = true"
                                                      @mouseleave="record.isTitleHovered = false"
                                                      @click="handleRead(record.paper_id)">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'favorite_time'">
                                                <span style="font-size: 16px; color: #6C6C6C">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'operations'">
                                                <span style="display: flex; justify-content: center; align-items: center;">
                                                    <a-tooltip title="取消收藏">
                                                        <delete-outlined style="fontSize :20px" @click="handleFavorite(record.paper_id)"/>
                                                    </a-tooltip>
                                                </span>
                                            </template>
                                            <template v-else>
                                                <span style="color: #0B0E47; font-size: 14px">{{ text }}</span>
                                            </template>
                                        </template>
                                    </a-table>
                                    <div style="display: flex; justify-content: center; margin: 20px">
                                        <a-pagination v-model:current="currentPage" :total="paperTotal" show-quick-jumper :showSizeChanger="false" @change="onPaperPageChange" />
                                    </div>
                                </a-tab-pane>
                            </a-tabs>
                        </a-layout-content>
                        <a-layout-content v-if="currentKey==4" :style="{ padding: '0 24px', minHeight: '280px', background: 'white'  }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="作者关注">
                                    <a-table :columns="authorColumns" :data-source="authorList" bordered :pagination="false">
                                        <template #bodyCell="{ column, text, record }">
                                            <template v-if="column.dataIndex === 'author_name'">
                                                <span :style="{ color: record.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: record.isTitleHovered ? 'underline' : 'none' , fontSize: '16px', cursor: 'pointer'}"
                                                      @mouseover="record.isTitleHovered = true"
                                                      @mouseleave="record.isTitleHovered = false"
                                                      @click="">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'author_time'">
                                                <span style="font-size: 16px; color: #6C6C6C">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'operations'">
                                                <span style="display: flex; justify-content: center; align-items: center;">
                                                    <a-tooltip title="取消关注">
                                                        <delete-outlined style="fontSize :20px" @click="handleInterest(record.author_id)"/>
                                                    </a-tooltip>
                                                </span>
                                            </template>
                                            <template v-else>
                                                <span style="color: #0B0E47; font-size: 14px">{{ text }}</span>
                                            </template>
                                        </template>
                                    </a-table>
                                    <div style="display: flex; justify-content: center; margin: 20px">
                                        <a-pagination v-model:current="currentPage" :total="authorTotal" :defaultPageSize="5" show-quick-jumper :showSizeChanger="false" @change="onAuthorPageChange" />
                                    </div>
                                </a-tab-pane>
                            </a-tabs>
                        </a-layout-content>
                        <a-layout-content v-if="currentKey==7" :style="{ padding: '0 24px', minHeight: '280px', background: 'white'  }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="浏览历史">
                                    <a-table :columns="browsingColumns" :data-source="browsingList" bordered :pagination="false">
                                        <template #bodyCell="{ column, text, record }">
                                            <template v-if="column.dataIndex === 'title'">
                                                <span :style="{ color: record.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: record.isTitleHovered ? 'underline' : 'none' , fontSize: '16px', cursor: 'pointer'}"
                                                      @mouseover="record.isTitleHovered = true"
                                                      @mouseleave="record.isTitleHovered = false"
                                                      @click="handleRead(record.paper_id)">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'browsing_time'">
                                                <span style="font-size: 16px; color: #6C6C6C">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'operations'">
                                                <span style="display: flex; justify-content: center; align-items: center;">
                                                    <a-tooltip title="删除记录">
                                                        <delete-outlined style="fontSize :20px" @click="handleDeleteBrowsing(record.paper_id)"/>
                                                    </a-tooltip>
                                                </span>
                                            </template>
                                            <template v-else>
                                                <span style="color: #0B0E47; font-size: 14px">{{ text }}</span>
                                            </template>
                                        </template>
                                    </a-table>
                                    <div style="display: flex; justify-content: center; margin: 20px">
                                        <a-pagination v-model:current="currentPage" :total="browsingTotal" show-quick-jumper :showSizeChanger="false" @change="onBrowsingPageChange" />
                                    </div>
                                </a-tab-pane>
                            </a-tabs>
                        </a-layout-content>
                        <a-layout-content v-if="currentKey==8" :style="{ padding: '0 24px', minHeight: '280px', background: 'white'  }">
                            <a-tabs v-model:activeKey="activeKey" :size="large">
                                <a-tab-pane key="1" tab="检索历史">
                                    <a-table :columns="searchColumns" :data-source="searchList" bordered :pagination="false">
                                        <template #bodyCell="{ column, text, record }">
                                            <template v-if="column.dataIndex === 'search_str'">
                                                <span :style="{ color: '#0B0E47', fontSize: '16px'}">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'search_time'">
                                                <span style="font-size: 16px; color: #6C6C6C">
                                                    {{ text }}
                                                </span>
                                            </template>
                                            <template v-else-if="column.dataIndex === 'operations'">
                                                <span style="display: flex; justify-content: center; align-items: center;">
                                                    <a-tooltip title="删除记录">
                                                        <delete-outlined style="fontSize :20px" @click="handleDeleteSearch(record.search_id)"/>
                                                    </a-tooltip>
                                                </span>
                                            </template>
                                            <template v-else>
                                                <span style="color: #0B0E47; font-size: 14px">{{ text }}</span>
                                            </template>
                                        </template>
                                    </a-table>
                                    <div style="display: flex; justify-content: center; margin: 20px">
                                        <a-pagination v-model:current="currentPage" :total="searchTotal" show-quick-jumper :showSizeChanger="false" @change="onSearchPageChange" />
                                    </div>
                                </a-tab-pane>
                            </a-tabs>
                        </a-layout-content>
                    </a-layout>
                </a-layout>
                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="loginForm"
                                    name="normal_login"
                                    class="login-form"
                                    style="margin-top: 20px"
                                    @finish="onLoginFinish"
                            >
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]"
                                >
                                    <a-input v-model:value="loginForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]"
                                >
                                    <a-input-password v-model:value="loginForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="loginForm.remember">自动登录</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" class="login-form-button" style="width: 100%">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a href="">注册新用户</a>
                                        <a class="login-form-forgot" href="">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
                <a-modal v-model:visible="registerShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">注册账号</div>
                            <a-form
                                    layout="horizontal"
                                    ref="registerFormRef"
                                    :model="registerForm"
                                    style="margin-top: 20px"
                                    @finish="onRegisterFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请设置用户名' },{ message: '用户名已被占用', validator: validateUsername}]">
                                    <a-input v-model:value="registerForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请设置密码' }]">
                                    <a-input-password v-model:value="registerForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item
                                        label="身份"
                                        name="identity"
                                        :rules="[{ required: true, message: '请选择身份' }]">
                                    <a-select v-model:value="registerForm.identity" :options="identityOptions" placeholder="请选择身份"/>
                                </a-form-item>

                                <a-form-item
                                        label="邮箱"
                                        name="email">
                                    <a-input v-model:value="registerForm.email" placeholder="请绑定邮箱">
                                        <template #prefix>
                                            <mail-outlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item>
                                    <a-button :disabled="registerDisabled" type="primary" html-type="submit" style="width: 70%">
                                        注册
                                    </a-button>
                                    <a-button style="margin-left: 5%; width: 25%" @click="() => registerFormRef.resetFields()">
                                        清空
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, toRefs} from "vue";
import {search} from "@/api/post/search";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import globalVariable from "@/components/mathJax/globalVariable";
import {logout, logout as logout_request} from "@/api/post/logout";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {register} from "@/api/post/register";
import {validate_username} from "@/api/post/validate_username";
import {
    DeleteOutlined,
    DownOutlined, HistoryOutlined, StarOutlined,
    UserOutlined
} from "@ant-design/icons-vue";
import {favorite} from "@/api/post/favorite";
import {edit_user_profile} from "@/api/post/edit_user_profile";
import {assign} from "lodash-es";
import {change_password} from "@/api/post/change_password";
import {get_favorite} from "@/api/post/get_favorite";
import {get_interest} from "@/api/post/get_interest";
import {get_browsing} from "@/api/post/get_browsing";
import {interest} from "@/api/post/interest";
import {delete_browsing} from "@/api/post/delete_browsing";
import {get_search} from "@/api/post/get_search";
import {delete_search} from "@/api/post/delete_search";
import {browsing} from "@/api/post/browsing";

export default defineComponent({
    components: {
        DeleteOutlined,
        StarOutlined,
        HistoryOutlined,
        UserOutlined,
        DownOutlined,
    },
    setup() {
        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            state.login = !store.state.logout;
            state.currentKey = $route.query.currentKey || 1;
            // 在接收到 $route.query.selectedKeys 后的处理逻辑中
            let selectedKeys = $route.query.selectedKeys; // 假设 selectedKeys 是一个整数
            if (typeof selectedKeys === 'string') {
                selectedKeys = [selectedKeys]; // 转换为字符串数组
            }
            // 然后将 selectedKeys 赋值给 state.selectedKeys
            state.selectedKeys = selectedKeys || ['1'];
            let openKeys = $route.query.openKeys;
            if (typeof openKeys === 'string') {
                openKeys = ['sub'+openKeys];
            }
            state.openKeys = openKeys || ['sub1'];
            checkLaTex()

            get_favorite(10,1).then((response) => {
                if (response.data.status.code === 0) {
                    state.paperTotal = response.data.data.total;
                    state.paperList = response.data.data.favoriteContent;
                }
            })

            get_search(10,1).then((response) => {
                if (response.data.status.code === 0) {
                    state.searchTotal = response.data.data.total;
                    state.searchList = response.data.data.searchList;
                }
            })

            get_browsing(10,1).then((response) => {
                if (response.data.status.code === 0) {
                    state.browsingTotal = response.data.data.total;
                    state.browsingList = response.data.data.browsingContent;
                }
            })

            get_interest(5,1).then((response) => {
                if (response.data.status.code === 0) {
                    state.authorTotal = response.data.data.total;
                    state.authorList = response.data.data.authorList;
                }
            })

            user_info().then((response) => {
                if (response.data.status.code === 0) {
                    state.last_login = new Date(parseInt(response.data.data.user.last_login) * 1000).toLocaleString()
                    assign(userFormState, response.data.data.user)
                }
            })
        });

        // ----------------定义的function，由下至上编写---------------
        const onPassFinish = values => {
            console.log(values, passFormState);
            change_password(passFormState.originPass, passFormState.newPass).then((response) => {
                if (response.data.status.code === 0) {
                    // 修改成功
                    notification['success']({
                        message: '成功',
                        description: '您的个人密码现已更新，请使用新密码重新登录。',
                    })
                    logout()
                            .then((response) => {
                                if (response.data) {
                                    // 退出成功
                                    store.commit('SET_LOGOUT', true)
                                    store.commit('CLEAR_USER_INFO')
                                    store.commit('CLEAR_TOKEN')
                                    onLoginShow();
                                }
                            })
                            .catch()
                } else {
                    notification['error']({
                        message: '您的修改密码请求出现错误',
                        description: `您的密码未被修改，因为${response.data.status.message}。`,
                    })
                }
            })
        };
        const onPassFinishFailed = errors => {
            console.log(errors);
        };
        const resetPassForm = () => {
            passFormRef.value.resetFields();
        };
        const handlePassValidate = (...args) => {
            console.log(args);
        };
        let validatePass = async (_rule, value) => {
            if (value === '') {
                return Promise.reject('请输入新密码');
            } else {
                if (passFormState.checkPass !== '') {
                    passFormRef.value.validateFields('checkPass');
                }
                return Promise.resolve();
            }
        };
        let validatePass2 = async (_rule, value) => {
            if (value === '') {
                return Promise.reject('请再次输入密码');
            } else if (value !== passFormState.newPass) {
                return Promise.reject("两次密码输入不一致!");
            } else {
                return Promise.resolve();
            }
        };

        const onAuthorPageChange = pageNumber => {
            get_interest(5, pageNumber).then((response) => {
                if (response.data.status.code === 0) {
                    state.currentPage = pageNumber;
                    state.authorTotal = response.data.data.total;
                    state.authorList = response.data.data.authorList;
                }
            })
        }

        const onSearchPageChange = pageNumber => {
            // 调用搜索接口
            get_search(10, pageNumber).then((response) => {
                if (response.data.status.code === 0) {
                    state.currentPage = pageNumber;
                    state.searchTotal = response.data.data.total;
                    state.searchList = response.data.data.searchList;
                }
            })
        }

        const onBrowsingPageChange = pageNumber => {
            // 调用搜索接口
            get_browsing(10, pageNumber).then((response) => {
                if (response.data.status.code === 0) {
                    state.currentPage = pageNumber;
                    state.browsingTotal = response.data.data.total;
                    state.browsingList = response.data.data.browsingContent;
                }
            })
        }

        const onPaperPageChange = pageNumber => {
            get_favorite(10, pageNumber).then((response) => {
                if (response.data.status.code === 0) {
                    state.currentPage = pageNumber;
                    state.paperTotal = response.data.data.total;
                    state.paperList = response.data.data.favoriteContent;
                }
            })
        }

        const handleDeleteSearch = (search_id) => {
            delete_search(search_id).then((response) => {
                // 请求成功后，从后端重新加载数据，不能单独处理前端，否则表格展示有误
                if (response.data.status.code === 0) {
                    get_search(10, state.currentPage).then((response) => {
                        if (response.data.status.code === 0) {
                            state.searchTotal = response.data.data.total;
                            state.searchList = response.data.data.searchList;
                        }
                    })
                }
            });
        }

        const handleDeleteBrowsing = (paper_id) => {
            delete_browsing(paper_id).then((response) => {
                // 请求成功后，从后端重新加载数据，不能单独处理前端，否则表格展示有误
                if (response.data.status.code === 0) {
                    get_browsing(10, state.currentPage).then((response) => {
                        if (response.data.status.code === 0) {
                            state.browsingTotal = response.data.data.total;
                            state.browsingList = response.data.data.browsingContent;
                        }
                    })
                }
            });
        }

        const handleInterest = (author_id) => {
            interest(author_id).then((response) => {
                // 请求成功后，从后端重新加载数据，不能单独处理前端，否则表格展示有误
                if (response.data.status.code === 0) {
                    get_interest(5, state.currentPage).then((response) => {
                        if (response.data.status.code === 0) {
                            state.authorTotal = response.data.data.total;
                            state.authorList = response.data.data.authorList;
                        }
                    })
                }
            });
        }

        const handleFavorite = (paper_id) => {
            favorite(paper_id).then(() => {
                // 请求成功后，从后端重新加载数据，不能单独处理前端，否则表格展示有误
                if (response.data.status.code === 0) {
                    get_favorite(10, state.currentPage).then((response) => {
                        if (response.data.status.code === 0) {
                            state.paperTotal = response.data.data.total;
                            state.paperList = response.data.data.favoriteContent;
                        }
                    })
                }
            });
        }

        const handleRead = (paper_id) => {
            // 记录用户浏览论文历史
            browsing(paper_id).then((response) => {
                if(response.data.status.code === 0){
                    console.log("浏览埋点设置成功")
                }
            })
            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
        }

        const onUserFinish = values => {
            console.log('性别:', values.gender);
            console.log('姓名:', values.realname);
            edit_user_profile(values)
                    .then((response) => {
                        if (response.data.status.code === 0) {
                            // 修改成功
                            notification['success']({
                                message: '成功',
                                description: '您的个人信息现已更新。',
                            })
                            // 更新本地用户信息
                            store.dispatch('UPDATE_USER_INFO')

                            user_info().then((response) => {
                                if (response.data.status.code === 0) {
                                    state.last_login = new Date(parseInt(response.data.data.user.last_login) * 1000).toLocaleString()
                                    assign(userFormState, response.data.data.user)
                                }
                            })
                        } else {
                            notification['error']({
                                message: '您的修改个人信息请求出现错误',
                                description: `个人信息未被修改，因为${response.data.status.message}。`,
                            })
                        }
                    })
                    .catch()

        };

        const onUserFinishFailed = errorInfo => {
            console.log('Failed:', errorInfo);
        };

        const handleMenuItem = e => {
            //切换menu初始化curpage
            state.currentPage = 1;
            state.currentKey = e.key;
            console.log(state.currentKey);
        };

        const registerDisabled = computed(() => {
            return !(registerForm.username && registerForm.password && registerForm.identity);
        });

        const validateUsername = (rule, value) => {
            return new Promise((resolve, reject) => {
                if (value.length === 0) {
                    resolve()
                }
                validate_username(value).then((response) => {
                    const { code, message } = response.data.status
                    if (code === 0) {
                        resolve()
                    } else {
                        reject(message)
                    }
                })
            })
        }

        const onRegisterFinish = values => {
            register(values.email, values.username, values.password, values.identity).then((response) => {
                if (response.data.status.code === 0) {
                    //注册成功
                    store.commit('CLEAR_USER_INFO')
                    store.commit('SET_TOKEN', response.data.data)
                    notification['success']({
                        message: '成功',
                        description: '注册成功',
                    })
                    state.loginShow = true;
                    state.registerShow = false;
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })
        }

        const onRegisterShow = () => {
            state.loginShow = false;
            state.registerShow = true;
        };

        const onLoginFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                    // if ($route.redirectedFrom) {
                                    //     router.push({
                                    //         path: decodeURIComponent($route.redirectedFrom.fullPath),
                                    //     })
                                    // } else {
                                    //     router.push('/')
                                    // }
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'center': {
                    state.currentKey = 1;
                    state.selectedKeys = ['1'];
                    state.openKeys = ['sub1'];
                    break
                }
                case 'favorite': {
                    state.currentKey = 3;
                    state.selectedKeys = ['3'];
                    state.openKeys = ['sub2'];
                    break
                }
                case 'interest': {
                    state.currentKey = 4;
                    state.selectedKeys = ['4'];
                    state.openKeys = ['sub2'];
                    break
                }
                    // case 'subscribe': {
                    //     router.push('/subscribe')
                    //     break
                    // }
                case 'logout': {
                    logout()
                }
            }
        }

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        // --------------------定义的vue变量------------------------
        // 确保在使用 '$route' 之前已经声明并初始化了它
        const router = useRouter()
        const $route = useRoute();
        const store = useStore()

        // --------------------定义的响应数据-----------------------
        const state = reactive({
            passFormRef: null,
            searchTotal: 0,
            browsingTotal: 0,
            authorTotal: 0,
            paperTotal: 0,
            currentPage: 1,
            searchList: [],
            browsingList: [],
            authorList: [],
            paperList: [],
            activeKey: '1',
            currentKey: 1,
            selectedKeys: ['1'],
            openKeys: ['sub1'],
            registerFormRef: null,
            registerShow: false,
            loginShow: false,
            login: true,
            backGroundImg: require('@/assets/background2.png'),
            backGroundImg2: require('@/assets/user-center-bg2.png'),
            systemTitle: process.env.VUE_APP_TITLE,
        })

        const passFormState = reactive({
            originPass: '',
            newPass: '',
            checkPass: '',
        });

        const userFormState = reactive({
            username: '',
            realname: '',
            gender: 0,
            major: 0,
            workplace: '',
            researchfield: '',
            email: '',
            phone: '',
        });

        const registerForm = reactive({
            username: '',
            password: '',
            identity: null,
            email: '',
        });

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------

        const passRules = {
            newpass: [{
                required: true,
                validator: validatePass,
                trigger: 'change',
            }],
            checkPass: [{
                validator: validatePass2,
                trigger: 'change',
            }],
        };

        const searchColumns = [{
            title: '检索式',
            dataIndex: 'search_str',
            width: 300,
        }, {
            title: '检索时间',
            dataIndex: 'search_time',
            width: 100,
        }, {
            title: '操作',
            dataIndex: 'operations',
            width: 50,
        }];

        const browsingColumns = [{
            title: '题名',
            dataIndex: 'title',
            width: 300,
        }, {
            title: '浏览时间',
            dataIndex: 'browsing_time',
            width: 100,
        }, {
            title: '操作',
            dataIndex: 'operations',
            width: 50,
        }];

        const authorColumns = [{
            title: '作者',
            dataIndex: 'author_name',
            width: 300,
        }, {
            title: '关注时间',
            dataIndex: 'interest_time',
            width: 100,
        }, {
            title: '操作',
            dataIndex: 'operations',
            width: 50,
        }];

        const paperColumns = [{
            title: '题名',
            dataIndex: 'title',
            width: 300,
        }, {
            title: '收藏时间',
            dataIndex: 'favorite_time',
            width: 100,
        }, {
            title: '操作',
            dataIndex: 'operations',
            width: 50,
        }];

        const identityOptions = [{
            label: '学生',
            value: '1',
        }, {
            label: '教授',
            value: '2',
        }, {
            label: '副教授',
            value: '3',
        }, {
            label: '讲师',
            value: '4',
        }]

        // ----------------------return函数-------------------
        return {
            passRules,
            onPassFinishFailed,
            onPassFinish,
            resetPassForm,
            handlePassValidate,
            passFormState,
            onAuthorPageChange,
            onSearchPageChange,
            onBrowsingPageChange,
            onPaperPageChange,
            searchColumns,
            browsingColumns,
            authorColumns,
            paperColumns,
            handleDeleteSearch,
            handleDeleteBrowsing,
            handleInterest,
            handleFavorite,
            handleRead,
            onUserFinish,
            onUserFinishFailed,
            userFormState,
            handleMenuItem,
            registerDisabled,
            validateUsername,
            identityOptions,
            onRegisterFinish,
            onRegisterShow,
            onLoginFinish,
            onLoginShow,
            onMenuClick,
            ...toRefs(state),
            registerForm,
            loginForm,
        }

    },
})
</script>

<style scoped>
.active {
    background-color: #4F4F4F;
    color: white;
}
.inactive {
    background-color: white;
    color: #4F4F4F;
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>